//
//  WBOAuthViewController.swift
//  WeiBo
//
//  Created by 韩菲菲 on 16/8/10.
//  Copyright © 2016年 韩菲菲. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthViewController: UIViewController {
    
    //懒加载一个控件
    lazy var webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        guard let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_uri)") else{
            
            //如果url不存在 不用去加载数据
            return
        }
        
        webView.loadRequest(NSURLRequest(URL: url))
        
        print(url.absoluteString)
        
        //设置代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置导航栏
        setupUI()
    }
    
    func setupUI() {
        
        view.backgroundColor = UIColor.whiteColor()
        
        navigationItem.title = "微博登录"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: #selector(WBOAuthViewController.autoFillAction))
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: #selector(WBOAuthViewController.cancelAction))
        
    }
    
    @objc private func autoFillAction(){
        
        //自动填充
        let jsString = "document.getElementById('userId').value='\(WBName)',document.getElementById('passwd').value='\(WBPassWd)'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
        
    }
    
    
    
    @objc private func cancelAction(){
        //销毁当前控制器
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
}

extension WBOAuthViewController:UIWebViewDelegate{
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
    
        //销毁HUD的View
        SVProgressHUD.dismiss()
        print("加载失败")
    }
    
    //    //加载每个请求都会走这个方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //判断请求是不是code请求 如果是 就截取code 利用code继续去请求数据
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(WBRedirect_uri){
            
            if let query = request.URL?.query{
                
                let code = query.substringFromIndex("code=".endIndex)
                
                //利用viewmodel去请求数据，只要告诉我请求成功或者失败，控制器对于不同情况做不同的事情
                WBUserAccountViewModel.sharedUserAccountViewModel.getUserAccount(code, finish: { (isSuccess) in
                    if !isSuccess{
                    
                        print("请求失败")
                        
                        return
                    
                    }
                    print("请求成功")
                    
                    //销毁控制器
                    self.dismissViewControllerAnimated(false, completion: {
                        //销毁HUD的View
                        SVProgressHUD.dismiss()
                        //发送通知，切换根控制器，切换为欢迎界面的控制器 welcomeVC
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSwithViewController, object: "welcome")
                        
                    })

                    
                    
                })
                
                return false
            }
        }
        return true
    }
}














